import React, { Component,useEffect,useState } from 'react';
import {Table, Checkbox, Space, Button, Divider, message, Modal, Row, Col, Input,Form} from 'antd';
import { getUserList,hasLoginName,saveUser,delUser,getUser } from "../api/Security";
import {ExclamationCircleOutlined} from "@ant-design/icons";
import {delDef} from "../api/workflow";
// import {Form} from "antd/lib/form";
export default class UserList extends Component {
    constructor(props) {
        super(props);
        this.formRef = React.createRef();
        this.state = {
            data: null,
            visible:false,    //可见性
            name:"",
            loginName:"",
            userFlag:1,
            userId:-1,  //新增用户 userid=-1  编辑 用户 则为selectedUserId  这个变量2个作用 ，表示是否新增或者编辑，新增 则给-1 编辑则为user id
            editState:0,  //0是编辑  1是add
            selectedUserId:-1   //选中的id
        }
    }

    componentDidMount() {
        getUserList().then(
            (res) => {
                this.setState({data: res.data});
            },
            (error) => {
                console.log("get UserList failed!");
            }
        );
    }

    //新的
    newUser=()=>{
        //editState 1 是新增加
        this.setState({visible:true,editState:1})
    }
    //eidt
    editUser=()=>{
        //当前是否已经选择用户
        //后台查询信息
        //后台查询信息初始化modal 中form 的值
        //Form 表单中增加一个隐藏域 存放id? antd 没有隐藏域！

        if (this.state.selectedUserId==-1){
            message.info("请选择一个需要编辑的用户")
            return;
        }
        let uid=this.state.selectedUserId;
        getUser(uid).then(
            (res) => {
                if(res.data!=null){
                    //后台查询信息初始化modal 中form 的值
                    this.setState({visible:true,editState:0})
                    this.formRef.current.setFieldsValue({'name': res.data.name,'loginName':res.data.loginName,userFlag:res.data.userFlag})

                }else{
                    message.error("查询用户失败")
                }
            },
            (error) => {
                message.error("有问题，重新试？")
            }
        )
    }
    //del
    delUser=()=>{
        if (this.state.selectedUserId==-1){
            message.info("请选择一个需要删除的用户")
            return;
        }
        const { confirm } = Modal;
        let uid=this.state.selectedUserId;

        confirm({
            title: 'Do you Want to delete this items',
            icon: <ExclamationCircleOutlined />,
            content: '删除选中的用户',
            onOk() {
                delUser(uid).then(
                    (res) => {
                        if(res.msg=="ok"){
                            message.success("删除用户成功");
                            window.location.reload();
                        }else{
                            message.error("删除用户失败")
                        }
                    },
                    (error) => {
                        message.error("删除用户失败")
                    }
                )
            },
            onCancel() {
                console.log('Cancel');

            },
        });
    }

    cancelModal = () => {
        this.formRef.current.setFieldsValue({'name': "",'loginName':"",userFlag:1})
        this.setState({
            visible: false,
        });
    };

    onOk = () => {
        this.formRef.current.setFieldsValue({'name': "",'loginName':"",userFlag:1})
        this.setState({
            visible: false,
        });
    };

     UserForm = () => {
         const  layout = {
             labelCol: { span: 8 },
             wrapperCol: { span: 16 },
         };
         const tailLayout = {
             wrapperCol: { offset: 8, span: 16 },
         };

        const onFinish = (values) => {


            //saveUser
            let f=1;
            if(!values.userFlag){
                f=0;
            }
            let uid=null;  //默认新增加
            if(this.state.editState==0){   //编辑
                uid=this.state.selectedUserId;
            }

            saveUser(values.loginName,values.name,f,uid).then(
                (res) => {
                    if(res.msg=="ok"){
                        message.success("保存用户成功");
                        this.setState({visible:false});
                        window.location.reload();
                    }else{
                        message.error("保存用户失败，可能登录名重复")
                    }
                },
                (error) => {
                    message.error("保存用户失败，可能登录名重复?")
                }
            );


            // console.log('Success:', values);
            // hasLoginName(values.loginName).then(
            //     (res) => {
            //        if(res.data==true){
            //            message.info("登录名已经存在，请更换一个登录名！")
            //             return;
            //        }else{
            //            //saveUser
            //            let f=1;
            //            if(!values.userFlag){
            //                f=0;
            //            }
            //            let uid=null;  //默认新增加
            //            if(this.state.editState==0){   //编辑
            //                uid=this.state.selectedUserId;
            //            }
            //
            //            saveUser(values.loginName,values.name,f,uid).then(
            //                (res) => {
            //                     if(res.msg=="ok"){
            //                         message.success("增加用户成功");
            //                         this.setState({visible:false});
            //                         window.location.reload();
            //                     }else{
            //                         message.error("增加用户失败，可能登录名重复")
            //                     }
            //                },
            //                (error) => {
            //                    message.error("增加用户失败，可能登录名重复?")
            //                }
            //            );
            //         }
            //     },
            //     (error) => {
            //         console.log("get UserList failed!");
            //     }
            // );
        };

        const onFinishFailed = (errorInfo) => {
            console.log('Failed:', errorInfo);
        };

        return (
            <Form
                {...layout}
                name="basic"
                initialValues={{ remember: true }}
                onFinish={onFinish}
                onFinishFailed={onFinishFailed}
                initialValues={{
                    name:this.state.name,
                    loginName:this.state.loginName,   //需要录入的member name
                    userFlag:this.state.userFlag
                }}
                // form={form}//这里需要注册一下form
                ref={this.formRef}//这里注册一下ref

            >
                <Form.Item
                    label="用户名"
                    name="name"
                    rules={[{ required: true, message: 'Please input your username!' }]}
                >
                    <Input/>
                </Form.Item>

                <Form.Item
                    label="登录名称"
                    name="loginName"
                    rules={[{ required: true, message: 'Please input your loginName!' }]}
                >
                    <Input/>
                </Form.Item>

                <Form.Item
                    label="是否启用"
                    name="userFlag"
                    rules={[]}
                    valuePropName="checked"
                >
                    <Checkbox></Checkbox>
                </Form.Item>
                <Form.Item {...tailLayout}>
                    <Button type="primary" htmlType="submit">
                        保存
                    </Button>
                    <Button >
                        取消
                    </Button>

                </Form.Item>
            </Form>
        );
    };

    render() {
        const columns = [
            {
                title: '登录名',
                dataIndex: 'loginName',
                key: 'loginName',
            },
            {
                title: '用户名',
                dataIndex: 'name',
                key: 'name',
            },
            {
                title: '启用状态',
                dataIndex: 'userFlag',
                key: 'userFlag',
            },
        ];

        const  rowSelection = {
            onChange: (selectedRowKeys, selectedRows) => {
                //  console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
            },
            onSelect: (record, selected, selectedRows) => {
                if(selected){
                    this.setState({
                        selectedUserId: record.userId,
                         });
                }else{
                    // this.setState({
                    //     selectedProc: -1,
                    //     deploymentId:-1
                    // });
                }
            },
        };

        return (
            <>
                <Space>
                    <Button onClick={this.newUser}>新增</Button>
                    <Button onClick={this.editUser}>修改</Button>
                    <Button onClick={this.delUser}>删除</Button>
                </Space>
                <Divider></Divider>


            <h1>
            {/*<Table columns={columns} dataSource={this.state.data} />*/}
                <Table
                    rowSelection={{
                        type: "radio",
                        ...rowSelection,
                    }}
                    rowKey="userId"
                    columns={columns} dataSource={this.state.data}/>
        </h1>

                <Modal
                    width={740}
                    title="管理用户"
                    visible={this.state.visible}
                    //confirmLoading={this.props.confirmLoading}
                     //onOk={this.onOk}
                    //okText='保存'
                    cancelText='返回'
                    onCancel={this.cancelModal}
                    footer={null}
                >
                    {this.UserForm()}
                </Modal>


         </>
                )
    }
}
